/**
 * 
 */
package com.terrence.sso.token.server.vo;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.SignatureException;

import java.io.Serializable;

/**
 * @author wuchuang
 *
 * 2017年3月8日 上午11:02:46
 */
public final class Token implements Serializable{
	
	private final static String SECRET_KEY = "20170307005959myssoByWuChuang";
	private final static String TOKEY_KEY = "sid";

	/**
	 * 
	 */
	private static final long serialVersionUID = -4654501323918439024L;
	
	private String sid;

	private Token(String sid) {
		super();
		this.sid = sid;
	}
	
	/**
	 * 构建Token
	 * @param sessionId
	 * @return
	 */
	public static Token getInstance(String sid){
		return new Token(sid);
	}
	
	/**
	 * 
	 * @return
	 */
	public String toToken(){
		String token = Jwts.builder()
                .signWith(SignatureAlgorithm.HS256,SECRET_KEY)
                .claim(TOKEY_KEY, this.sid)
                .compact();
		return token;
	}
	
	/**
	 * 从Token中获取sid
	 * @param token
	 * @return
	 */
	public static String getSessionIdFromToken(String token){
		try {
	        Claims claims = Jwts.parser()
	                .setSigningKey(SECRET_KEY)
	                .parseClaimsJws(token)
	                .getBody();
	        String sessionId = claims.get(TOKEY_KEY, String.class);
	        return sessionId;
	    }
	    catch (SignatureException ex) {
	        return null;
	    }
	}

}
